package loader;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;

/**
 * @author Supreme_Sir
 * @version 1.0
 * @className MyClassLoader
 * @description
 * @date 2020/11/24 21:40
 **/
public class MyClassLoader extends ClassLoader {

    @Override
    public Class<?> findClass(String name) {
        Class clazz = null;
        int idx = name.indexOf(".");
        String projectName = name.substring(0, idx);
        name = name.substring(++idx);
        String absolutePath = MyClassLoader.class.getResource("/").getPath() + "webapps" + File.separator
                + projectName + File.separator + name.replaceAll("\\.", "/") + ".class";

        byte[] bytes = getByte(new File(absolutePath));

        if (bytes != null) {
            clazz = defineClass(name, bytes, 0, bytes.length);
        }
        return clazz;
    }

    private byte[] getByte(File classFile) {
        FileInputStream in = null;
        ByteArrayOutputStream out = null;
        byte[] result = null;
        try {
            in = new FileInputStream(classFile);
            out = new ByteArrayOutputStream();

            byte[] buffer = new byte[1024];
            int size = 0;

            while ((size = in.read(buffer)) != -1) {
                out.write(buffer, 0, size);
            }
            result = out.toByteArray();
        } catch (Exception e) {
            e.printStackTrace();
        }finally {
            try {
                in.close();
                out.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return result;
    }
}
